# ORB(Oriented FAST and Rotated BRIEF),基于特征匹配
# 旨在替代SIFT和SURF

import cv2

video_capture = cv2.VideoCapture()

ret = video_capture.open(0)
if not ret:
    print("video_capture open error\n")
    exit(1)

ret, capture_bgr = video_capture.read()
if not ret:
    print("video_capture read error\n")
    exit(1)

cv2.imshow("capture_bgr", capture_bgr)

rect = cv2.selectROI("capture_bgr", capture_bgr)
x, y, w, h = rect

capture_roi = capture_bgr[y:y+h, x:x+w]
cv2.imshow("capture_roi", capture_roi)

roi_gray = cv2.cvtColor(capture_roi, cv2.COLOR_BGR2GRAY)

# 创建ORB检测器对象
orb = cv2.ORB_create()

while True:
    ret, current_capture_bgr = video_capture.read()
    if not ret:
        break

    current_capture_gray = cv2.cvtColor(current_capture_bgr, cv2.COLOR_BGR2GRAY)

    # 检测关键点和计算描述符
    kp1, des1 = orb.detectAndCompute(roi_gray, None)
    kp2, des2 = orb.detectAndCompute(current_capture_gray, None)

    # 使用BFMatcher寻找最佳匹配
    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

    # 匹配描述符
    matches = bf.match(des1, des2)

    # 根据距离排序匹配结果(从小到大)
    matches = sorted(matches, key=lambda x: x.distance)

    # 绘制前N个匹配项
    img3 = cv2.drawMatches(roi_gray, kp1, current_capture_gray, kp2, matches[:10], None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

    # 显示结果
    cv2.imshow('Top 10 Matches', img3)
    cv2.waitKey()

cv2.destroyAllWindows()